/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2025 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "pid.h"
#include "stdio.h"
#include "motor.h"
#include "stdlib.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
//struct WT61C WT61C_RX;
uint8_t RxData;
PID_t MotorPID={
  .Target=500,
  .Kp=0,
  .Ki=0,
  .Kd=0,
  .a=0.4,
  .OUT_MAX=1000,
  .OUT_MIN=-1000
};    
uint16_t count=0;
uint8_t pitch,roll,yaw=0;
uint8_t RxWT61;
int16_t Angle_Z=0;
uint8_t keynum;
/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{

  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_TIM2_Init();
  MX_TIM4_Init();
  MX_USART1_UART_Init();
  MX_TIM3_Init();
  MX_TIM1_Init();
  /* USER CODE BEGIN 2 */
  HAL_TIM_Base_Start_IT(&htim4);
  HAL_TIM_Encoder_Start(&htim2,TIM_CHANNEL_1);
  HAL_TIM_Encoder_Start(&htim2,TIM_CHANNEL_2);
  HAL_TIM_Encoder_Start(&htim3,TIM_CHANNEL_1);
  HAL_TIM_Encoder_Start(&htim3,TIM_CHANNEL_2);

  HAL_UART_Receive_IT(&huart1,&RxData,1);
  //HAL_UART_Receive_IT(&huart6,&RxWT61,1);

MotorInit();
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */
printf("encoder1:%d,%d\n",MotorPID.Actual1,MotorPID.Target);
	  
    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Configure the main internal regulator output voltage
  */
  __HAL_RCC_PWR_CLK_ENABLE();
  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLM = 4;
  RCC_OscInitStruct.PLL.PLLN = 168;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  RCC_OscInitStruct.PLL.PLLQ = 4;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
	static uint16_t count1=0,count2=0;

	if(htim==&htim4)
	{
		count1++;
		count2++;
		if(count1>=200)
		{
			count1=0;
			//Key_Tick();
			MotorPID.Actual1=__HAL_TIM_GetCounter(&htim2);
			__HAL_TIM_SetCounter(&htim2,0);
			PID_Updata(&MotorPID);
			SetMotorPwm(MotorPID.Out);
			printf("encoder1:%d\n",MotorPID.Actual1);
			
			MotorPID.Actual2=__HAL_TIM_GetCounter(&htim3);
			__HAL_TIM_SetCounter(&htim3,0);
			PID_Updata(&MotorPID);
			SetMotorPwm(MotorPID.Out);
			//printf("encoder2:%d\n",MotorPID.Actual2);
		}
		if(count2>=500)
		{
			count2=0;
			//printf("Angle:%d\n",Angle_Z);
		}
	}
	
}	
	
	
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
//	if(huart==&huart6)
//	{
//		CopeSerial2Data_imu(RxWT61);
//		HAL_UART_Receive_IT(&huart1,&RxWT61,1);
//	}
	
  if(huart==&huart1)
  {
	static uint8_t RxData;
	static uint8_t RxIndex;
	static uint8_t RxPacket[128];
	static enum{
		Wait_Head, //????
		Wait_Flag, //??????
		Wait_Data  //??????
	}RxState=Wait_Head;//?????????
    static enum{
		CMD_NONE,  //???
		CMD_Kp,    //Kp
		CMD_Ki,    //Ki
		CMD_Kd    //Kd
//		CMD_SET
	}CurrentCmd=CMD_NONE; //??????
	switch(RxState)
	{
		case Wait_Head:
			if(RxData=='K')
			{
				RxState=Wait_Flag;
			}
			break;
		case Wait_Flag:
			if(RxData=='P')
			{
				CurrentCmd=CMD_Kp;
				RxState=Wait_Data;
				RxIndex=0;
			}
			else if(RxData=='I')
			{
				CurrentCmd=CMD_Ki;
				RxState=Wait_Data;
				RxIndex=0;
			}
			else if(RxData=='D')
			{
				CurrentCmd=CMD_Kd;
				RxState=Wait_Data;
				RxIndex=0;
			}
//			else if(RxData=='S')
//			{
//				CurrentCmd=CMD_SET;
//				RxState=Wait_Data;
//				RxIndex=0;
//			}
			else
				RxState=Wait_Head;
			break;
		case Wait_Data:
			if(RxData=='M')
		  {
				RxPacket[RxIndex]='\0';
				uint8_t *endptr;
				float NewValue = strtof((char*)RxPacket, (char**)&endptr);  // ????
				// ???????
                if(endptr!=RxPacket && *endptr == '\0') 
				{
					switch(CurrentCmd)
					{
						case CMD_Kp:
							MotorPID.Kp=NewValue;
							printf("Kp updated:%.2f\n",MotorPID.Kp);
                            break;
						case CMD_Ki:
							MotorPID.Ki=NewValue;
						    printf("Ki updated:%.2f\n",MotorPID.Ki);
						    break;
						case CMD_Kd:
							MotorPID.Kd=NewValue;
							printf("Kd updated:%.2f\n",MotorPID.Kd);
						    break;
						
//						case CMD_SET:
//							MotorPID.Target=NewValue;
//							printf("Kd updated:%.2f\n",MotorPID.Target);
//						    break;
						
						case CMD_NONE:
							break;
					}
				}
				else
					printf("Error:%s\n",RxPacket);
				RxState=Wait_Head;
				CurrentCmd=CMD_NONE;
			}
			else
			{
				if(RxIndex<sizeof(RxPacket)-1)
				{
					RxPacket[RxIndex++]=RxData;
				}
				else
				{
					RxState=Wait_Head;
				}
			}
			break;
		default:
			RxState=Wait_Head;
			break;
		    
	}
    HAL_UART_Receive_IT(&huart1,&RxData,1);
  }
}



/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
